package com.eqdd.yiqidian.ui.discover.workcircle;

import android.Manifest;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.bumptech.glide.Glide;
import com.coorchice.library.SuperTextView;
import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.WorkCircleActivityCustom;
import com.eqdd.yiqidian.adapter.recycleadapter.ItemClickSupport;
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx;
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector;
import com.eqdd.yiqidian.adapter.slimadapter.viewinjector.IViewInjector;
import com.eqdd.yiqidian.base.AppConstent;
import com.eqdd.yiqidian.base.BaseActivity;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.bean.WorkCircleBean;
import com.eqdd.yiqidian.helper.mvchelper.ModelRx2DataSource;
import com.eqdd.yiqidian.helper.mvchelper.Rx2DataSource;
import com.eqdd.yiqidian.http.DialogCallBack;
import com.eqdd.yiqidian.http.HttpConfig;
import com.eqdd.yiqidian.http.HttpResult;
import com.eqdd.yiqidian.http.JsonCallBack;
import com.eqdd.yiqidian.http.JsonConverter;
import com.eqdd.yiqidian.service.UserService;
import com.eqdd.yiqidian.ui.MainActivity;
import com.eqdd.yiqidian.ui.ScanZXingActivity;
import com.eqdd.yiqidian.ui.mine.UserCardActivity;
import com.eqdd.yiqidian.ui.mine.wo.CollectionActivity;
import com.eqdd.yiqidian.ui.select.RichTextResult;
import com.eqdd.yiqidian.ui.select.SelectRichTextActivity;
import com.eqdd.yiqidian.utils.ImageUtil;
import com.eqdd.yiqidian.utils.PicUtil;
import com.eqdd.yiqidian.utils.ShareUtil;
import com.eqdd.yiqidian.utils.ToastUtil;
import com.eqdd.yiqidian.widget.ChooseAlertView;
import com.eqdd.yiqidian.widget.InputDialogFragment;
import com.eqdd.yiqidian.widget.UniversalImageLoader;
import com.hitomi.tilibrary.style.index.NumberIndexIndicator;
import com.hitomi.tilibrary.style.progress.ProgressBarIndicator;
import com.hitomi.tilibrary.transfer.TransferConfig;
import com.hitomi.tilibrary.transfer.Transferee;
import com.jakewharton.rxbinding.view.RxView;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.PostRequest;
import com.lzy.okrx2.adapter.FlowableResponse;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.shizhefei.mvc.MVCSwipeRefreshHelper;
import com.tbruyelle.rxpermissions.RxPermissions;

import org.reactivestreams.Publisher;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Flowable;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Function;
import io.rong.imkit.plugin.location.AMapLocationInfo;
import io.rong.imkit.plugin.location.IMyLocationChangedListener;
import io.rong.imkit.plugin.location.LocationManager;
import io.rong.imkit.utils.RongDateUtils;
import io.rong.imlib.model.Conversation;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;

public class WorkCircleActivity extends BaseActivity implements IMyLocationChangedListener {
    private WorkCircleActivityCustom dataBinding;
    private ArrayList<WorkCircleBean> workCircleBeen = new ArrayList<>();
    private SlimAdapterEx<WorkCircleBean> slimAdapterEx;
    private RichTextResult richTextResult;
    private String location;
    private MVCSwipeRefreshHelper<List<WorkCircleBean>> mvcHelper;
    private ModelRx2DataSource<WorkCircleBean> dataSource;
    private InputDialogFragment inputDialogFragment;
    private int clickedPosition;
    private Transferee transferee;
    private TransferConfig config;
    private MaterialDialog dialog;
    private MaterialDialog saveDialog;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        isKeyBoardJustPan = false;
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        super.onCreate(savedInstanceState);
    }

    @Override
    public void initBinding() {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_work_circle);
        initTopTitleBar(View.VISIBLE, "工作圈");
        initTopRightText("发布", v -> {
            Bundle bundle = new Bundle();
            bundle.putString(Config.TITLE, "发工作圈");
            startActivityForResult(SelectRichTextActivity.class, bundle, Config.SELECT_RICH_TEXT);
        });
        transferee = Transferee.getDefault(this);
        ImageLoader.getInstance().init(ImageLoaderConfiguration.createDefault(this));
        config = TransferConfig.build()
                .setMissPlaceHolder(R.mipmap.ic_launcher_logo)
                .setErrorPlaceHolder(R.mipmap.ic_launcher_logo)
                .setProgressIndicator(new ProgressBarIndicator())
                .setIndexIndicator(new NumberIndexIndicator())
                .setImageLoader(UniversalImageLoader.with(getApplicationContext()))
                .setJustLoadHitImage(true)
                .setOnLongClcikListener((imageView, i) -> {
                    ArrayList<Object> objects = new ArrayList<>();
                    objects.add("保存图片");
                    objects.add("收藏");
                    SlimAdapterEx slimAdapterEx = SlimAdapterEx.create().registerDefault(R.layout.list_item_54, new SlimInjector() {
                        @Override
                        public void onInject(Object data, IViewInjector injector) {

                            injector.text(R.id.tv_content, (String) data)
                                    .clicked(R.id.tv_content, v -> {
                                        saveDialog.dismiss();
                                        saveImageByUniversal(imageView);
                                    });
                        }
                    }).updateData(objects);
                    saveDialog = new MaterialDialog.Builder(this)
                            .adapter(slimAdapterEx, new LinearLayoutManager(this))
                            .build();
                    saveDialog.show();
                })
                .create();
        ImageUtil.setImage(user.getWorkImage(), dataBinding.ivHeadBg);
        dataBinding.tvSignature.setText(user.getSignature());

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Config.SUCCESS) {
            switch (requestCode) {
                case Config.SELECT_RICH_TEXT:
                    richTextResult = (RichTextResult) data.getSerializableExtra(Config.RICH_TEXT_RESULT);
                    PostRequest<HttpResult> params = OkGo.<HttpResult>post(HttpConfig.BASE_URL + HttpConfig.CREATE_WORK_CIRCLE)
                            .params("companyId", user.getCompanyId())
                            .params("userGuid", user.getGuid())
                            .params("message", richTextResult.getContent())
                            .params("name", user.getUname())
                            .params("location", TextUtils.isEmpty(location) ? "" : location);
                    List<LocalMedia> selectMedia = richTextResult.getSelectMedia();
                    for (int i = 0; i < selectMedia.size(); i++) {
                        params.params("file", new File(selectMedia.get(i).isCompressed() ? selectMedia.get(i).getCompressPath() : selectMedia.get(i).getPath()));
                    }
                    params.execute(new DialogCallBack<HttpResult>(this) {
                        @Override
                        public void onSuccess(Response<HttpResult> response) {
                            HttpResult httpResult = response.body();
                            ToastUtil.showShort(httpResult.getMsg());
                            if (httpResult.getStatus() == 200) {
                                mvcHelper.refresh();
                            }
                        }
                    });
            }
        } else if (resultCode == Config.CHANGE) {
            WorkCircleBean bean = (WorkCircleBean) data.getSerializableExtra("bean");
            slimAdapterEx.getData().remove(requestCode);
            slimAdapterEx.getData().add(requestCode, bean);
            slimAdapterEx.notifyItemChanged(requestCode + 1);
        } else if (resultCode == Config.DELETE) {
            slimAdapterEx.getData().remove(requestCode);
            slimAdapterEx.notifyItemRemoved(requestCode + 1);
        }
        if (resultCode == RESULT_OK && requestCode == PictureConfig.CHOOSE_REQUEST) {
            List<LocalMedia> localMedia = PictureSelector.obtainMultipleResult(data);
            OkGo.<HttpResult<String>>post(HttpConfig.BASE_URL + HttpConfig.WORK_CIRCLE_UPDATE_IMG)
                    .params("userGuid", user.getGuid())
                    .params("user", user.getUname())
                    .params("file", new File(localMedia.get(0).getCompressPath()))
                    .execute(new DialogCallBack<HttpResult<String>>(WorkCircleActivity.this) {
                        @Override
                        public void onSuccess(Response<HttpResult<String>> response) {
                            HttpResult<String> httpResult = response.body();
                            ToastUtil.showShort(httpResult.getMsg());
                            if (httpResult.getStatus() == 200) {
                                ImageUtil.setImage(HttpConfig.BASE_URL_NO + httpResult.getItems(), dataBinding.ivHeadBg);
                                startService(new Intent(WorkCircleActivity.this, UserService.class));
                            }
                        }
                    });
        }
    }

    @Override
    public void initData() {
        Observable<Void> observable = RxView.clicks(dataBinding.includeTitle.getRoot()).share();
        observable.buffer(observable.debounce(200, TimeUnit.MILLISECONDS))
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(voids -> {
                    if (voids.size() >= 2) {
                        dataBinding.recyclerView.smoothScrollToPosition(0);
                        mvcHelper.refresh();
                    }
                }, System.out::print);
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        if (user != null) {
            LocationManager.getInstance().bindConversation(this, Conversation.ConversationType.PRIVATE, user.getGuid());
            LocationManager.getInstance().setMyLocationChangedListener(this);
            LocationManager.getInstance().updateMyLocation();
        }
        assert user != null;
        dataBinding.tvName.setText(user.getUsername());
        ImageUtil.setImage(user.getIphoto(), dataBinding.ivPhoto);
        dataBinding.vImageWatcher.setErrorImageRes(R.mipmap.error_picture);
        dataBinding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        slimAdapterEx = SlimAdapterEx.create().register(R.layout.list_item_work_circle, new SlimInjector<WorkCircleBean>() {
            @Override
            public void onInject(WorkCircleBean data, IViewInjector injector) {
                try {
                    injector.imageCircle(R.id.iv_head, data.getIphoto())
                            .text(R.id.tv_city, data.getLocation())
                            .visibility(R.id.tv_city, TextUtils.isEmpty(data.getLocation()) ? View.GONE : View.VISIBLE)
                            .text(R.id.tv_depart, data.getDepartName() + " " + data.getPostName())
                            .text(R.id.tv_time, RongDateUtils.getConversationFormatDate(sf.parse(data.getCreateTime()).getTime(), WorkCircleActivity.this))
                            .with(R.id.stv_name, v -> {
                                        SuperTextView superTextView = (SuperTextView) v;
                                        superTextView.setText(data.getStaffName());
                                    }
                            )
                            .text(R.id.tv_content, data.getMessage())
                            .visibility(R.id.tv_content, TextUtils.isEmpty(data.getMessage()) ? View.GONE : View.VISIBLE)
                            .with(R.id.stv_support, v -> {
                                SuperTextView superTextView = (SuperTextView) v;
                                superTextView.setText(data.getZanCount() + "");
                                superTextView.setDrawable(getResources().getDrawable(data.isIsZan() ? R.mipmap.ic_heart_red : R.mipmap.ic_heart_hint));
                            })
                            .with(R.id.stv_msg, v -> {
                                SuperTextView superTextView = (SuperTextView) v;
                                superTextView.setText(data.getCommentCount() + "");
                                superTextView.setDrawable(getResources().getDrawable(R.mipmap.ic_comment));
                            })
                            .clicked(R.id.iv_head, v -> {
                                Bundle bundle = new Bundle();
                                bundle.putString(Config.GUID, data.getCreater());
                                startActivity(UserCardActivity.class, bundle);
                            })
                            .clicked(R.id.iv_img1, v -> {
                                enterPicPreview(data, 0);
//                                newShow(0, data, injector);
//                                bigImgShow(data, injector, (ImageView) v);
                            })
                            .clicked(R.id.iv_img2, v -> {
                                enterPicPreview(data, 1);

//                                newShow(1, data, injector);

//                                bigImgShow(data, injector, (ImageView) v);
                            })
                            .clicked(R.id.iv_img3, v -> {
                                enterPicPreview(data, 2);
//                                newShow(2, data, injector);

//                                bigImgShow(data, injector, (ImageView) v);
                            })
                            .clicked(R.id.img_only_one, v -> {
                                enterPicPreview(data, 0);
//                                ArrayList<ImageView> imageViews = new ArrayList<>();
//                                imageViews.add((ImageView) injector.findViewById(R.id.img_only_one));
//                                config.setNowThumbnailIndex(0);
//                                config.setSourceImageList(data.getNewImages());
//                                config.setOriginImageList(imageViews);
//                                transferee.apply(config).show();
                            })
                            .clicked(R.id.stv_msg, v -> {
                                clickedPosition = slimAdapterEx.getData().indexOf(data);
                                openInput(data.getStaffName(), 0 + "");
                            })
                            .clicked(R.id.iv_option, v -> {
                                ChooseAlertView.getBottomChoose(WorkCircleActivity.this, null, new String[]{"分享到QQ", "收藏"}, (o, position) -> {
                                    // 当R.id.enableCamera被点击的时候触发获取权限
                                    if (position == 2) {
                                        if (data.getNewImages() == null || data.getNewImages().size() == 0) {

                                            OkGo.<HttpResult>post(HttpConfig.BASE_URL + HttpConfig.ADD_COLLECTION)
                                                    .params("owner", AppConstent.user.getGuid())
                                                    .params("type", 2)
                                                    .params("title", "工作圈")
                                                    .params("tel", AppConstent.user.getUname())
                                                    .params("ccontent", data.getMessage())
                                                    .params("source", "工作圈")
                                                    .params("sourceOwner", data.getCreater())
                                                    .execute(new DialogCallBack<HttpResult>(WorkCircleActivity.this) {
                                                        @Override
                                                        public void onSuccess(Response<HttpResult> response) {
                                                            HttpResult httpResult = response.body();
                                                            ToastUtil.showShort(httpResult.getMsg());
                                                        }
                                                    });
                                        } else {
                                            StringBuilder url = new StringBuilder();
                                            for (String s : data.getNewImages()) {
                                                url.append(s).append(";");
                                            }

                                            OkGo.<HttpResult>post(HttpConfig.BASE_URL + HttpConfig.ADD_COLLECTION)
                                                    .params("owner", AppConstent.user.getGuid())
                                                    .params("type", 9)
                                                    .params("title", "工作圈")
                                                    .params("url", url.toString())
                                                    .params("tel", AppConstent.user.getUname())
                                                    .params("ccontent", data.getMessage())
                                                    .params("source", "工作圈")
                                                    .params("sourceOwner", data.getCreater())
                                                    .execute(new DialogCallBack<HttpResult>(WorkCircleActivity.this) {
                                                        @Override
                                                        public void onSuccess(Response<HttpResult> response) {
                                                            HttpResult httpResult = response.body();
                                                            ToastUtil.showShort(httpResult.getMsg());
                                                        }
                                                    });
                                        }
                                    } else if (position == 1) {

                                        if (data.getNewImages() == null || data.getNewImages().size() == 0) {

                                            ShareUtil.share2QQ(ShareUtil.getWorkCircleUrl(data.getId() + "", data.getCreater()));
                                        } else {
                                            ShareUtil.share2QQ(ShareUtil.getWorkCircleUrl(data.getId() + "", data.getCreater()), data.getNewImages().get(0));

                                        }
                                    }
                                }).show();

                            });
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                if (!data.isIsZan()) {
                    injector.enable(R.id.stv_support);
                    injector.clicked(R.id.stv_support, v -> {
                        OkGo.<HttpResult>post(HttpConfig.BASE_URL + HttpConfig.WORK_CIRCLE_ZAN)
                                .params("companyId", user.getCompanyId())
                                .params("userGuid", user.getGuid())
                                .params("workCircleId", data.getId())
                                .params("companyId", user.getCompanyId())
                                .execute(new JsonCallBack<HttpResult>() {
                                    @Override
                                    public void onSuccess(Response<HttpResult> response) {
                                        HttpResult httpResult = response.body();
                                        if (httpResult.getStatus() == 200) {
                                        }
                                    }
                                });
                        SuperTextView superTextView = ((SuperTextView) v);
                        superTextView.setText((data.getZanCount() + 1) + "");
                        superTextView.setDrawable(getResources().getDrawable(R.mipmap.ic_heart_red));
                        data.setZanCount(data.getZanCount() + 1);
                        data.setIsZan(true);
                        injector.disable(R.id.stv_support);
                        data.getUserZan().add(0, new WorkCircleBean.UserZanBean(user.getGuid(), user.getIphoto()));
                        ((SlimAdapterEx) ((RecyclerView) injector.findViewById(R.id.recyclerViewHead)).getAdapter()).updateData(data.getUserZan().subList(0, data.getUserZan().size() > 3 ? 3 : data.getUserZan().size()));
                    });
                } else {
                    injector.disable(R.id.stv_support);
                }
                if (((RecyclerView) injector.findViewById(R.id.recyclerViewHead)).getAdapter() == null) {
                    ((RecyclerView) injector.findViewById(R.id.recyclerViewHead)).setLayoutManager(new LinearLayoutManager(WorkCircleActivity.this, LinearLayoutManager.HORIZONTAL, false));
                    SlimAdapterEx slimAdapterExHead = SlimAdapterEx.create().register(R.layout.list_item_head_img, new SlimInjector<WorkCircleBean.UserZanBean>() {
                        @Override
                        public void onInject(WorkCircleBean.UserZanBean data, IViewInjector injector) {
                            injector.with(R.id.iv_head_img, v -> ImageUtil.setCircleImage(data.getHeadImage(), (ImageView) v));
                        }
                    }).attachTo((RecyclerView) injector.findViewById(R.id.recyclerViewHead));
                }
                ItemClickSupport.addTo((RecyclerView) injector.findViewById(R.id.recyclerViewHead))
                        .setOnItemClickListener(new ItemClickSupport.OnItemClickListener() {
                            @Override
                            public void onItemClicked(RecyclerView recyclerView, int position, View v) {
                                Bundle bundle = new Bundle();
                                bundle.putString("id", data.getId() + "");
                                bundle.putString("idName", "workCircleId");
                                startActivity(ZanListActivity.class, bundle);
                            }
                        });
                injector.clicked(R.id.ll_head_img, v -> {
                    Bundle bundle = new Bundle();
                    bundle.putString("id", data.getId() + "");
                    bundle.putString("idName", "workCircleId");
                    startActivity(ZanListActivity.class, bundle);
                });
                ((SlimAdapterEx) ((RecyclerView) injector.findViewById(R.id.recyclerViewHead)).getAdapter()).updateData(data.getUserZan().subList(0, data.getUserZan().size() > 3 ? 3 : data.getUserZan().size()));
                if (data.getNewImages() == null || data.getNewImages().size() == 0) {
                    injector.gone(R.id.ll_img)
                            .gone(R.id.tv_img_num)
                            .gone(R.id.img_only_one);
                } else {
                    injector.visible(R.id.ll_img);
                    if (data.getNewImages().size() == 1) {
//                        injector.visible(R.id.iv_img1)
//                                .with(R.id.iv_img1, v -> ImageUtil.setImage(data.getNewImages().get(0), (ImageView) v))
//                                .invisible(R.id.iv_img2)
//                                .invisible(R.id.iv_img3);
                        injector.visible(R.id.img_only_one)
                                .image(R.id.img_only_one, data.getNewImages().get(0))
                                .invisible(R.id.ll_img);
                    } else if (data.getNewImages().size() == 2) {
                        injector.visible(R.id.ll_img)
                                .gone(R.id.img_only_one)
                                .visible(R.id.iv_img1)
                                .visible(R.id.iv_img2)
                                .with(R.id.iv_img1, v -> ImageUtil.setImage(data.getNewImages().get(0), (ImageView) v))
                                .with(R.id.iv_img2, v -> ImageUtil.setImage(data.getNewImages().get(1), (ImageView) v))
                                .invisible(R.id.iv_img3);
                    } else if (data.getNewImages().size() >= 3) {
                        injector.visible(R.id.ll_img)
                                .gone(R.id.img_only_one)
                                .visible(R.id.iv_img1)
                                .visible(R.id.iv_img2)
                                .visible(R.id.iv_img3)
                                .with(R.id.iv_img1, v -> ImageUtil.setImage(data.getNewImages().get(0), (ImageView) v))
                                .with(R.id.iv_img2, v -> ImageUtil.setImage(data.getNewImages().get(1), (ImageView) v))
                                .with(R.id.iv_img3, v -> ImageUtil.setImage(data.getNewImages().get(2), (ImageView) v));
                    }
                    if (data.getNewImages().size() > 3) {
                        injector.visible(R.id.tv_img_num)
                                .text(R.id.tv_img_num, "+" + data.getNewImages().size());
                    } else {
                        injector.invisible(R.id.tv_img_num);
                    }
                }
            }
        }).attachTo(dataBinding.recyclerView);
        ItemClickSupport.addTo(dataBinding.recyclerView)
                .setOnItemClickListener((recyclerView, position, v) -> {
                    if (position == 0) {

                        if (dialog == null) {
                            dialog = getDialog();
                        }
                        dialog.show();
                    } else {
                        position--;
                        ActivityOptionsCompat activityOptions = ActivityOptionsCompat.makeSceneTransitionAnimation(
                                WorkCircleActivity.this,
                                v.findViewById(R.id.rl_root), "transitionImg");
                        Intent intent = new Intent(WorkCircleActivity.this, WorkCircleInfoActivity.class);
                        intent.putExtra("bean", slimAdapterEx.getDataItem(position));
                        // 这里指定了共享的视图元素
                        startActivityForResult(intent, position, activityOptions.toBundle());
                    }
                });
        slimAdapterEx.updateData(workCircleBeen);
        dataSource = new ModelRx2DataSource<>(new ModelRx2DataSource.OnLoadSource() {
            @Override
            public Flowable<List> loadSourcce(int page, Rx2DataSource.DoneActionRegister register) {
                return OkGo.<HttpResult<List<WorkCircleBean>>>post(HttpConfig.BASE_URL + HttpConfig.WORK_CIRCLE_LIST)
                        .cacheKey(HttpConfig.BASE_URL + HttpConfig.WORK_CIRCLE_LIST + (page == 1 ? 0 : slimAdapterEx.getDataItem(slimAdapterEx.getData().size() - 1).getId()))
                        .cacheMode(CacheMode.REQUEST_FAILED_READ_CACHE)
                        .retryCount(1)
                        .params("companyId", user.getCompanyId())
                        .params("userGuid", user.getGuid())
                        .params("id", page == 1 ? 0 : slimAdapterEx.getDataItem(slimAdapterEx.getData().size() - 1).getId())
                        .converter(new JsonConverter<HttpResult<List<WorkCircleBean>>>() {
                            @Override
                            public void test() {
                                super.test();
                            }
                        })
                        .adapt(new FlowableResponse<HttpResult<List<WorkCircleBean>>>())
                        .flatMap(new Function<Response<HttpResult<List<WorkCircleBean>>>, Publisher<List<WorkCircleBean>>>() {
                            @Override
                            public Publisher<List<WorkCircleBean>> apply(@NonNull Response<HttpResult<List<WorkCircleBean>>> httpResultResponse) throws Exception {
                                return Flowable.just(httpResultResponse.body().getItems() == null ? new ArrayList<WorkCircleBean>() : httpResultResponse.body().getItems());

                            }
                        });
            }
        }, 6);
        mvcHelper = new MVCSwipeRefreshHelper<>(dataBinding.swipeRefresh);
        mvcHelper.setNeedCheckNetwork(false);
        mvcHelper.setDataSource(dataSource);
        mvcHelper.setAdapter(slimAdapterEx);
        mvcHelper.refresh();
    }

    private void enterPicPreview(WorkCircleBean data, int pos) {
        ArrayList<LocalMedia> localMedia = new ArrayList<>();
        for (int i = 0; i < data.getNewImages().size(); i++) {
            localMedia.add(PicUtil.localMedia(data.getNewImages().get(i)));
        }
        PicUtil.previewMy(WorkCircleActivity.this, pos, localMedia, "工作圈", data.getCreater());
    }

    private MaterialDialog getDialog() {
        ArrayList<Object> objects = new ArrayList<>();
        objects.add("更改封面");
        SlimAdapterEx slimAdapterEx = SlimAdapterEx.create().registerDefault(R.layout.list_item_54, new SlimInjector() {
            @Override
            public void onInject(Object data, IViewInjector injector) {

                injector.text(R.id.tv_content, (String) data)
                        .clicked(R.id.tv_content, v -> {
                            dialog.dismiss();
                            PicUtil.cut(WorkCircleActivity.this, 600, 300);
                        });
            }
        }).updateData(objects);
        MaterialDialog build = new MaterialDialog.Builder(this)
                .adapter(slimAdapterEx, new LinearLayoutManager(this))
                .build();
        return build;
    }

    private void newShow(int pos, WorkCircleBean data, IViewInjector injector) {
        ArrayList<ImageView> imageViews = new ArrayList<>();
        if (data.getNewImages().size() > 0) {
            imageViews.add((ImageView) injector.findViewById(R.id.iv_img1));
        }
        if (data.getNewImages().size() > 1) {
            imageViews.add((ImageView) injector.findViewById(R.id.iv_img2));
        }
        if (data.getNewImages().size() > 2) {
            imageViews.add((ImageView) injector.findViewById(R.id.iv_img3));
        }
        config.setNowThumbnailIndex(pos);
        config.setSourceImageList(data.getNewImages());
        config.setOriginImageList(imageViews);
        transferee.apply(config).show();
    }

    private void bigImgShow(WorkCircleBean data, IViewInjector injector, ImageView v) {
        ArrayList<ImageView> imageViews = new ArrayList<>();
        if (data.getNewImages().size() > 0) {
            imageViews.add((ImageView) injector.findViewById(R.id.iv_img1));
        }
        if (data.getNewImages().size() > 1) {
            imageViews.add((ImageView) injector.findViewById(R.id.iv_img2));
        }
        if (data.getNewImages().size() > 2) {
            imageViews.add((ImageView) injector.findViewById(R.id.iv_img3));
        }
        dataBinding.vImageWatcher.show(v, imageViews, data.getNewImages());
    }

    @Override
    public void onMyLocationChanged(AMapLocationInfo aMapLocationInfo) {
        System.out.println("当前类=WorkCircleActivity.onMyLocationChanged()");
        if (aMapLocationInfo != null) {
            location = aMapLocationInfo.getProvince()
                    + aMapLocationInfo.getCity()
                    + aMapLocationInfo.getDistrict();
            System.out.println(location);
        }
    }

    private void openInput(String replyName, String replyGuid) {
        if (user.getGuid().equals(replyGuid)) {
            return;
        }
        Bundle bundle = new Bundle();
        bundle.putString("hint", "回复" + replyName + ":");
        inputDialogFragment.setArguments(bundle);
        inputDialogFragment.show(getSupportFragmentManager(), "input");
    }

    @Override
    public void setView() {
        initInputDialog();


        dataBinding.llRoot.removeViewAt(0);
        slimAdapterEx.addHeader(dataBinding.rlHeadRoot);
    }

    @Override
    public void onBackPressed() {
        if (dataBinding.vImageWatcher.isShown()) {
            dataBinding.vImageWatcher.onSingleTapConfirmed();
        } else {
            super.onBackPressed();
        }
    }

    private void initInputDialog() {
        inputDialogFragment = new InputDialogFragment();
        inputDialogFragment.setOnClickListener(s -> {
                    OkGo.<HttpResult>post(HttpConfig.BASE_URL + HttpConfig.WORK_CIRCLE_COMMENT)
                            .params("companyId", user.getCompanyId())
                            .params("userGuid", user.getGuid())
                            .params("message", s)
                            .params("workCircleId", slimAdapterEx.getDataItem(clickedPosition).getId())
                            .params("parentId", 0)
                            .execute(new DialogCallBack<HttpResult>(this) {
                                @Override
                                public void onSuccess(Response<HttpResult> response) {
                                    HttpResult httpResult = response.body();
                                    ToastUtil.showShort(httpResult.getMsg());
                                    if (httpResult.getStatus() == 200) {
                                        inputDialogFragment.dismiss();
                                        WorkCircleBean dataItem = slimAdapterEx.getDataItem(clickedPosition);
                                        dataItem.setCommentCount(dataItem.getCommentCount() + 1);
                                        slimAdapterEx.notifyItemChanged(clickedPosition + 1);
                                    }
                                }
                            });
                }
        );
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {

        }
    }


}
